package settings

import (
	"path/filepath"

	"github.com/go-kratos/kratos/v2/log"
	"gopkg.in/natefinch/lumberjack.v2"
)

func NewLogger(c *LogConf, filename string) *lumberjack.Logger {
	if c == nil {
		panic("log config is nil")
	}
	return &lumberjack.Logger{
		Filename:   filepath.Join(c.LogDir, filename), // 文件位置
		MaxSize:    int(c.MaxSize),                    // 进行切割之前,日志文件的最大大小(MB为单位)
		MaxAge:     int(c.MaxAge),                     // 保留旧文件的最大个数
		MaxBackups: int(c.MaxBackups),                 // 保留旧文件的最大天数
		Compress:   c.Compress,                        // 是否压缩/归档旧文件
		LocalTime:  c.Localtime,                       // 使用本地时间还是 UTC 时间
	}
}

type Loggers struct {
	Server  log.Logger
	Service log.Logger
	Biz     log.Logger
	Data    log.Logger
	Access  log.Logger
}

func NewLoggers(c *LogConf, kv ...any) *Loggers {
	if c == nil {
		panic("log config is nil")
	}
	serverLogWrite := NewLogger(c, "server.log")
	serviceLogWrite := NewLogger(c, "service.log")
	bizLogWrite := NewLogger(c, "biz.log")
	dataLogWrite := NewLogger(c, "data.log")
	accessLogWrite := NewLogger(c, "access.log")
	return &Loggers{
		Server:  log.With(log.NewStdLogger(serverLogWrite), kv...),
		Service: log.With(log.NewStdLogger(serviceLogWrite), kv...),
		Biz:     log.With(log.NewStdLogger(bizLogWrite), kv...),
		Data:    log.With(log.NewStdLogger(dataLogWrite), kv...),
		Access:  log.With(log.NewStdLogger(accessLogWrite), kv...),
	}
}

type LogHelpers struct {
	Server  *log.Helper
	Service *log.Helper
	Biz     *log.Helper
	Data    *log.Helper
	Access  *log.Helper
}

func NewLogHelpers(logger *Loggers) *LogHelpers {
	return &LogHelpers{
		Server:  log.NewHelper(logger.Server),
		Service: log.NewHelper(logger.Service),
		Biz:     log.NewHelper(logger.Biz),
		Data:    log.NewHelper(logger.Data),
		Access:  log.NewHelper(logger.Access),
	}
}
